//
//  FlightSearchController.m
//  ELife
//
//  Created by xiaozhi on 11-5-23.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "FlightSearchController.h"
#import "StepView.h"
#import "FlightCityListController.h"
#import "FlightResultListController.h"
#import "FlightModel.h"
#import "FlightCheckedModel.h"

@implementation FlightSearchController
@synthesize fromCityButton, fromDateButton, toCityButton;

UIView *inputContainer;
UILabel *returnTimeLabel;
UIButton *returnTimeButton;
UIButton *searchButton;
id datePickListener;
FlightCity *_toCity;
FlightCity *_fromCity;
bool _isReturn = NO; //是否是 往返

// init with customer
- (FlightSearchController *)initWithCustomer
{
    self = [[FlightSearchController alloc]initWithNibName:@"FlightSearchController" bundle:nil];
    
    return self;
}

+ (FlightCheckedModel *)getCheckedModel
{
    if (checkModel == nil) {
        checkModel = [[FlightCheckedModel alloc]init];
    }
    return checkModel;
}

- (void)dealloc
{
    [toCityButton release];
    [fromCityButton release];
    [fromDateButton release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)initStepView
{
    StepView *stepView = [[StepView alloc] createStepViewWithStep:0];
    
    [self.view addSubview:stepView];
    [stepView release];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = [[UIColor alloc]
                                 initWithPatternImage:[UIImage imageNamed:@"bg.png"]];
    
    inputContainer = [self.view viewWithTag:TAG_INPUT_CONTAINER];
    inputContainer.layer.cornerRadius = 8;
    inputContainer.layer.masksToBounds = YES;
    
    [self initStepView];
    
    
    searchButton = (UIButton *)[self.view viewWithTag:TAG_SEARCH_BUTTON];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)buttonAction:(id)sender
{
    if (sender == returnTimeButton) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"hi" message:@"see me?" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
}

// init return uiview
- (void)initReturnUI
{
    
    returnTimeLabel = [[UILabel alloc]init];
    returnTimeLabel.frame = CGRectMake(15, 183, 58, 37);
    returnTimeLabel.text = @"返回时间";
    UIFont *font = [UIFont boldSystemFontOfSize:14];
    returnTimeLabel.font = font;
    
    
    returnTimeButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect]retain];
    returnTimeButton.frame = CGRectMake(81, 183, 130, 37);
    [returnTimeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [returnTimeButton addTarget:self action:@selector(pickDate:) forControlEvents:UIControlEventTouchDown];
    
    [inputContainer addSubview:returnTimeLabel];
    [returnTimeLabel release];
    [inputContainer addSubview:returnTimeButton];
    [returnTimeButton release];
    
    searchButton.frame = CGRectOffset(searchButton.frame, 0, Y_OFFSET);
}

- (void)segmentControlAction:(id)sender
{
    UISegmentedControl *segmentControl = (UISegmentedControl *)sender;
    unsigned int selectedIndex = [segmentControl selectedSegmentIndex];
    
    switch (selectedIndex) {
        case 0:
            [returnTimeButton removeFromSuperview];
            [returnTimeLabel removeFromSuperview];
            searchButton.frame = CGRectOffset(searchButton.frame, 0, -Y_OFFSET);
            _isReturn = NO;
            break;
        case 1:
            [self initReturnUI];
            _isReturn = YES;
            break;
        default:
            break;
    }
}

- (void)openCityList:(SEL)onSelected
{
    FlightCityListController *cityListController = [[FlightCityListController alloc]init];
    
    [cityListController addTarget:self action:onSelected];
    
    [self.navigationController pushViewController:cityListController animated:YES];
    [cityListController release];
    
    self.navigationController.navigationBarHidden = YES;
}

- (void)pickFromCity
{
    [self openCityList:@selector(setFromCity:)];
}


- (void)showDatePicker
{
    NSString *title = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? @"\n\n\n\n\n\n\n\n\n" : @"\n\n\n\n\n\n\n\n\n\n\n\n" ;
    UIActionSheet *actionSheet = [[UIActionSheet alloc] 
                                  initWithTitle:title 
                                  delegate:self 
                                  cancelButtonTitle:@"取消" 
                                  destructiveButtonTitle:@"设置"
                                  otherButtonTitles:nil];
    
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    datePicker.datePickerMode = UIDatePickerModeDate;
    datePicker.tag = TAG_DATE_PICKER;
    [actionSheet addSubview:datePicker];
    [datePicker release];
    
    [actionSheet showInView:self.view];
    [actionSheet release];
}

- (void)pickDate:(id)sender
{
    datePickListener = sender;
    [self showDatePicker];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
        formatter.dateFormat = @"YYYY-MM-dd";
        
        UIDatePicker *datePicker = (UIDatePicker *)[actionSheet viewWithTag:TAG_DATE_PICKER];
        NSString *timestamp = [formatter stringFromDate:datePicker.date];
        
        UIButton *listenerButton = datePickListener;
        [listenerButton setTitle:timestamp forState:UIControlStateNormal];
    }
}

- (void)pickToCity
{
    [self openCityList:@selector(setToCity:)];
}

- (void)setFromCity:(FlightCity *)fromCity
{
    [_fromCity release];
    _fromCity = [fromCity retain];
    
    
    NSString *cityName = fromCity._cityName;
    [self.fromCityButton setTitle:cityName forState:UIControlStateNormal];
}

- (void)setToCity:(FlightCity *)toCity
{
    [_toCity release];
    _toCity = [toCity retain];
    NSString *cityName = toCity._cityName;
    [self.toCityButton setTitle:cityName forState:UIControlStateNormal];
}

// show alert
- (void)showAlert:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:msg delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];

}

// validate input
- (BOOL)searchValidate
{
    NSString *msg = nil;
    if (_toCity == nil) {
        msg = @"请选择出发城市";
    } else if (_fromCity == nil) {
        msg = @"请选择到达城市";
    } else if([_toCity._cityName isEqualToString:_fromCity._cityName]) {
        msg = @"出发城市和到达城市不能相同";
    } else if ([[((UIButton *)datePickListener) titleForState:UIControlStateNormal] length] == 0) {
        msg = @"请选择出发时间";
    } else if (_isReturn == YES 
               && [[returnTimeButton titleForState:UIControlStateNormal] length] == 0) {
        msg = @"请选择返程时间";
    }
    
    if (msg != nil) {
        [self showAlert:msg];
        return NO;
    }
    
    return YES;
}



-(void)search
{
    if ([self searchValidate] == NO) {
        return;
    }
    
    FlightResultListController *nextController 
        = [[FlightResultListController alloc]
           initWithNibName:@"FlightResultListController" bundle:nil];
    
    [nextController setSearchParam:_fromCity withToCity:_toCity  withDate:[((UIButton *)datePickListener) titleForState:UIControlStateNormal]];
    [self.navigationController pushViewController:nextController animated:YES];
    self.navigationController.navigationBarHidden = NO;
    [nextController release];
}
@end
